<?php
//Start Functions
//

// Load the SQL into an array
//////////////////////////////////////////////////////////////

function sqlLoad($sql,$db){

	$connTLS = mysql_pconnect($db['hostname'],$db['username'],$db['password']) or trigger_error(mysql_error(),E_USER_ERROR);

	mysql_select_db($db['dbname'], $connTLS);

	$getData = mysql_query($sql, $connTLS) or die(mysql_error());

	$totalRows_getData = mysql_num_rows($getData);

	for($i = 0; $array_getData[$i] = mysql_fetch_assoc($getData); $i++) ;

	array_pop($array_getData);

	mysql_free_result($getData);

	return $array_getData;

}

// Modify SQL (INSERT, UPDATE or DELETE)
////////////////////////////////////////////////////////////

function sqlMod($sql,$db){

	$connTLS = mysql_pconnect($db['hostname'],$db['username'],$db['password']) or trigger_error(mysql_error(),E_USER_ERROR);

	mysql_select_db($db['dbname'], $connTLS);

        mysql_query($sql,$connTLS);
	
	return mysql_insert_id();

}

/**
 *
 * sqlPairs is used to return key/value data from a database
 *
 * @param <type> $table
 * @param <type> $key
 * @param <type> $value
 * @param <type> $filter
 * @param <type> $sort
 * @param <type> $db
 * @return <type> array
 */

function sqlPairs($table,$key,$value,$filter,$sort='',$db){

	$connTLS = mysql_pconnect($db['hostname'],$db['username'],$db['password']) or trigger_error(mysql_error(),E_USER_ERROR);

	mysql_select_db($db['dbname'], $connTLS);

        $sql = "SELECT $key,$value FROM $table";

        if(strlen(trim($filter))>0) $sql .= " WHERE ".$filter;

        if(strlen(trim($sort))>0) $sql .= " ORDER BY ".$sort;

	$getData = mysql_query($sql, $connTLS) or die(mysql_error());

        if(mysql_num_rows($getData) == 0) return false;

        $array_getData = array();

	$totalRows_getData = mysql_num_rows($getData);

        while ($row = mysql_fetch_assoc($getData)) {

            $array_getData[$row[$key]] = $row[$value];

        }

	mysql_free_result($getData);

	return $array_getData;

}

// Check a string length.
///////////////////////////////////////////////////////////////

function checkString($string,$len,$error,$type){

	if(!isset($string)||strlen($string)==0) return $error." Not Found";
	
	if(strlen($string) < $len) return $error." String Too Short";

}

// Check Email Formating
///////////////////////////////////////////////////////////////


function checkEmail($email) {

  if (!ereg("^[^@]{1,64}@[^@]{1,255}$", $email)) {
    return false;
  }

  $email_array = explode("@", $email);
  $local_array = explode(".", $email_array[0]);
  for ($i = 0; $i < sizeof($local_array); $i++) {
     if (!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$", $local_array[$i])) {
      return false;
    }
  }  
  if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1])) {
    $domain_array = explode(".", $email_array[1]);
    if (sizeof($domain_array) < 2) {
        return false;
    }
    for ($i = 0; $i < sizeof($domain_array); $i++) {
      if (!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$", $domain_array[$i])) {
        return false;
      }
    }
  }
  return true;
}		

// Remove all phone parts but numbers
///////////////////////////////////////////////////////////

function fixPhone($string){

	$string = preg_replace( '/[\s\-A-Za-z\(\)\.]/', '', $string);
	$string = substr($string, 0, 10);
	
	return $string;

}

// Execution Page Timer
//////////////////////////////////////////////////////////////

function startTimer(){
    global $timeStart;
    $mtime = microtime();
    $mtime = explode(" ",$mtime);
    $mtime = $mtime[1] + $mtime[0];
    $timeStart = $mtime;

    return true;
}

function stopTimer($precision=3){
    global $timeStart;
    $debug = '';
    $mtime = microtime();
    $mtime = explode(" ",$mtime);
    $mtime = $mtime[1] + $mtime[0];
    $timeEnd = $mtime;
    $timeTotal = $timeEnd-$timeStart;
    $scriptTime = number_format($timeTotal,$precision);

    return $scriptTime;
}

// String Location Counter
////////////////////////////////////////////////////////

function InStrCount($String,$Find,$CaseSensitive = false) {
     $i = 0;
     $x = 0;
     while(strlen($String) >= $i)
     {
         unset($substring);
         if($CaseSensitive)
         {
             $Find = strtolower($Find);
             $String = strtolower($String);
        }
         $substring = substr($String,$i,strlen($Find));
         if($substring == $Find) $x++;
         $i++;
     }
     return $x;
 }


// SQL String Cleaning and Injection Protection
//////////////////////////////////////////////////////////////////////////

function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") {

  $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;

  //$theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}

// Funtion MakeTags Makes A Paragraph into tags
/////////////////////////////////////////////////////////////

function MakeTags($inString,$breakAt){
$inString = strtolower($inString);
$tempArray = explode($breakAt,$inString);
$countArray = $tempArray;
$tempArray = array_unique($tempArray);
$patterns = array("about","after","again","air","all","along","also","an","and","another","any","are","around","as","at","away","back","be","because","been","before","below","between","both","but","by","came","can","come","could","day","did","different","do","does","don't","down","each","end","even","every","few","find","first","for","found","from","get","give","go","good","great","had","has","have","he","help","her","here","him","his","home","house","how","I","if","in","into","is","it","its","just","know","large","last","left","like","line","little","long","look","made","make","man","many","may","me","men","might","more","most","Mr.","must","my","name","never","ne","next","no","not","now","","number","of","off","old","on","one","only","or","other","our","out","over","own","part","people","pla","put","read","right","said","same","saw","say","see","she","should","show","small","so","some","something","sound","still","such","take","tell","than","that","the","them","then","there","these","they","thing","think","this","those","thought","three","through","time","to","together","too","two","under","up","us","use","very","want","water","way","we","well","went","were","what","when","where","which","while","who","why","will","with","word","work","world","would","write","year","you","your","was","and","a","the","or","is","of","this","for","in","to","as","on","no","i'm","am","what","where","when","so","an","how","do","i","really","want","get","like","should","was","just","you","your","it","at","if","my","but","not","it's","-",".","..","...","?","!"," ",",,",",,,",",,,,","&",);
$TagString = "";
$Count = 0;
	foreach ($tempArray as $v1) {
		if(!in_array($v1,$patterns)){
		$Count = $Count +1;
		$v1 = str_replace(".","",$v1);
		$v1 = str_replace(",","",$v1);
		$v1 = str_replace("?","",$v1);
		$v1 = str_replace("!","",$v1);
		$v1 = str_replace(":","",$v1);
		$v1 = str_replace(";","",$v1);	
		$v1 = str_replace(")","",$v1);	
		$v1 = str_replace("(","",$v1);						
			if($Count == 1){
			$TagString = $v1;
			} else {
			$TagString .= ", ".$v1;
			}
		}
	}
	foreach ($countArray as $v2) {
		if(!in_array($v2,$patterns)){
		$Count2 = $Count2 +1;
		$v2 = str_replace(".","",$v2);
		$v2 = str_replace(",","",$v2);
		$v2 = str_replace("?","",$v2);
		$v2 = str_replace("!","",$v2);
		$v2 = str_replace(":","",$v2);
		$v2 = str_replace(";","",$v2);	
		$v2 = str_replace("(","",$v2);	
		$v2 = str_replace(")","",$v2);										
			if($Count2 == 1){
			$CountString = $v2;
			} else {
			$CountString .= ", ".$v2;
			}
		}
	}
	$countArray = explode(", ",$CountString);
	return $TagString;
	//print_r(array_count_values($countArray));
	}

// Function MakeList
////////////////////////////////////////////////////////////////////

function MakeList($inString) {
$patterns = array (" and "," a "," the "," or "," is "," of "," this "," for "," in "," to "," - "," ",",,",",,,",",,,,");
$finalremove=$inString;
$piece_front="";
$piece_back="";
$piece_replace=", ";

   for ($x=0; $x < count($patterns); $x++) {
   $safety=0;
       while(strstr(strtolower($finalremove),strtolower($patterns[$x]))) {
   $safety=$safety+1;
		if ($safety >= 100000) { break; }
			$occ=strpos(strtolower($finalremove),strtolower($patterns[$x]));
			$piece_front=substr($finalremove,0,$occ);
			$piece_back=substr($finalremove,($occ+strlen($patterns[$x])));
			$finalremove=$piece_front . $piece_replace . $piece_back;
		} # while    
   } # for
return $finalremove;
}

// Remove Curse Words
//////////////////////////////////////////////////////////////////////

function RemoveCurseWords($original) {

$patterns = array ("shit","fuck","cock","cunt","bitch","asshole");
$finalremove=$original;
$piece_front="";
$piece_back="";
$piece_replace="***";
	for ($x=0; $x < count($patterns); $x++) {
	$safety=0;
		while(strstr(strtolower($finalremove),strtolower($patterns[$x]))) {
	$safety=$safety+1;
		if ($safety >= 100000) { break; }
			$occ=strpos(strtolower($finalremove),strtolower($patterns[$x]));
			$piece_front=substr($finalremove,0,$occ);
			$piece_back=substr($finalremove,($occ+strlen($patterns[$x])));
			$finalremove=$piece_front . $piece_replace . $piece_back;
		} # while
      
   } # for


$patterns = array ("<p>&nbsp;</p>","<p></p>","<p> </p>","<p> &nbsp;</p>","<p>&nbsp; </p>","</br></br>","<br /><br />","&nbsp;&nbsp;","&nbsp; <br>","&nbsp; "," <br>");
$finalremove=$finalremove;
$piece_front="";
$piece_back="";
$piece_replace="";
	for ($x=0; $x < count($patterns); $x++) {
	$safety=0;
		while(strstr(strtolower($finalremove),strtolower($patterns[$x]))) {
	$safety=$safety+1;
		if ($safety >= 100000) { break; }
			$occ=strpos(strtolower($finalremove),strtolower($patterns[$x]));
			$piece_front=substr($finalremove,0,$occ);
			$piece_back=substr($finalremove,($occ+strlen($patterns[$x])));
			$finalremove=$piece_front . $piece_replace . $piece_back;
		} # while
      
   } # for
return $finalremove; 
}

// Strip out HTML from string
//////////////////////////////////////////////////////////

function RemoveHTML($string){
   //while there are tags left to remove
   while(strstr($string, '>'))
   {
       //find position of first carrot
       $currentBeg = strpos($string, '<');
      
       //find position of end carrot
       $currentEnd = strpos($string, '>');
      
       //find out if there is string before first carrot
       //if so save it in $tmpstring
       $tmpStringBeg = @substr($string, 0, $currentBeg);
      
       //find out if there is string after last carrot
       //if so save it in $tmpStringEnd
       $tmpStringEnd = @substr($string, $currentEnd + 1, strlen($string));
      
       //cut the tag from the string
       $string = $tmpStringBeg.$tmpStringEnd;  
	   
   }
      
$patterns = array ("<",">","'","--");
$finalremove=$string;
$piece_front="";
$piece_back="";
$piece_replace="*";
	for ($x=0; $x < count($patterns); $x++) {
	$safety=0;
		while(strstr(strtolower($finalremove),strtolower($patterns[$x]))) {
	$safety=$safety+1;
		if ($safety >= 100000) { break; }
			$occ=strpos(strtolower($finalremove),strtolower($patterns[$x]));
			$piece_front=substr($finalremove,0,$occ);
			$piece_back=substr($finalremove,($occ+strlen($patterns[$x])));
			$finalremove=$piece_front . $piece_replace . $piece_back;
		} # while
      
   } # for
$string = $finalremove; 
	  
   return $string;
}

function FixGoogleFeed($String){

$pos = strrpos($String, "http://news.google.com/news/url?");
if ($pos === false) { // note: three equal signs
   // not found...

	return $String;

} else {


$temp = strstr($String, '</nobr></font><br><font size=-1>');
$temp = RemoveHTML($temp);
return $temp;
}
}

function left ($str, $howManyCharsFromLeft){
  return substr ($str, 0, $howManyCharsFromLeft);
}

function right ($str, $howManyCharsFromRight){
  $strLen = strlen ($str);
  return substr ($str, $strLen - $howManyCharsFromRight, $strLen);
}

function mid ($str, $start, $howManyCharsToRetrieve = 0){
  $start--;
  if ($howManyCharsToRetrieve === 0)
    $howManyCharsToRetrieve = strlen ($str) - $start;

  return substr ($str, $start, $howManyCharsToRetrieve);
}

function str_chop($string, $length, $center = false, $append = null){
     // Set the default append string
     if ($append === null) {
         $append = ($center === true) ? ' ... ' : ' ...';
     }
  
     // Get some measurements
     $len_string = strlen($string);
     $len_append = strlen($append);
  
     // If the string is longer than the maximum length, we need to chop it
     if ($len_string > $length) {
         // Check if we want to chop it in half
         if ($center === true) {
             // Get the lengths of each segment
             $len_start = $length / 2;
             $len_end = $len_start - $len_append;
  
             // Get each segment
             $seg_start = substr($string, 0, $len_start);
             $seg_end = substr($string, $len_string - $len_end, $len_end);
  
             // Stick them together
             $string = $seg_start . $append . $seg_end;
         } else {
             // Otherwise, just chop the end off
             $string = substr($string, 0, $length - $len_append) . $append;
         }
     }
  
     return $string;
 }
 
function format_size($rawSize) {
	if ($rawSize / 1048576 > 1)
		return round($rawSize/1048576, 1) . ' MB';
	else if ($rawSize / 1024 > 1)
		return round($rawSize/1024, 1) . ' KB';
	else
		return round($rawSize, 1) . ' b';
}	

function sortArrayByField($original,$field,$descending = false){
	$sortArr = array();           
		foreach ( $original as $key => $value ){
		$sortArr[ $key ] = $value[ $field ];
		}
	if ( $descending ){
		arsort( $sortArr );
	} else {
		asort( $sortArr );
	}
$resultArr = array();
	foreach ( $sortArr as $key => $value ){
		$resultArr[ $key ] = $original[ $key ];
	}
return $resultArr;
}   

 //Encrypt Function
 function Encrypt($encrypt,$key) {
    $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND);
    $passcrypt = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $encrypt, MCRYPT_MODE_ECB, $iv);
    $encode = base64_encode($passcrypt);
 return $encode;
 }
 
 //Decrypt Function
 function Decrypt($decrypt,$key) {
    $decoded = base64_decode($decrypt);
    $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND);
    $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $decoded, MCRYPT_MODE_ECB, $iv);
 return trim($decrypted);
 } 
 
function calObj ( $start, $event ){

global  $link_month_next,  $link_month_prev;
// turn the start into parts

$get_date = explode("-",$start);

// set the useful variables
$year = $get_date[0];
$month = $get_date[1];
$day = $get_date[2];

$day_first = $get_date[0]."-".$get_date[1]."-01";
$day_last =  $get_date[0]."-".$get_date[1]."-".date("t",strtotime($start));

$week_start = strtotime($start."- ".date("w",strtotime($start))." days +1 day");

$day_count = 1;
$week_count = date("w",strtotime($day_first));
$cal_start = 0;



// Instead of returning HTML we will return an array

//echo "Today is ".$start."<BR>";
//echo "It is day ".date("w",strtotime($start))."<BR>";
//echo "Week started on Monday the ".date('m-d',$week_start)."<BR>";
//echo "Days this month ".date("t",strtotime($start))."<BR>";
//echo "This month started on ".date("w",strtotime($day_first))."<BR>";
// 
echo '<table border="0" cellspacing="1" cellpadding="4">
<tr><td colspan="7" align="center" background="images/nav.gif"><table width="100%" border="0" cellspacing="0" cellpadding="0"><tr><td width="7"><a href="'.$link_month_prev.'"><img src="images/cal_up.gif" border="0" /></a></td><td align="center"><a href="calendar.php"><img src="images/cal_center.gif" border="0" /></a></td><td width="7"><a href="'.$link_month_next.'"><img src="images/cal_down.gif" border="0" /></a></td><td align="right"><a href="calendar.php?v=agenda" class="tn">Agenda</a></td></tr></table></td></tr>
<tr><td colspan="7" align="center" bgcolor="#cbddef"><table width="100%" border="0" cellspacing="0" cellpadding="0"><tr><td style="font-size:25pt; padding-right:6px;" align="right">'.date("jS", strtotime($start)).'</td><td><span style="font-size:13pt;">'.date("l", strtotime($start)).'</span><BR><span style="font-size:7pt;">'.date("F", strtotime($start)).', '.$year.'</span></td></tr></table></td></tr>
<tr align="center" bgcolor="#e2d4b3"><td>S</td><td>M</td><td>T</td><td>W</td><td>T</td><td>F</td><td>S</td></tr><tr>';
// Loop through non-month days at the beginning
if(date('w',strtotime($day_first))>0){

	$day_first = $year."-".$month."-01";
	
	$fw_start = date("t",mktime(0,0,0,($month -1),1,$year)); //number of days last month
	
	$fw_offset = date("w",mktime(0,0,0,$month,1,$year)); //offset of day of the week
	
	$fw_start = date("Y-m-d",mktime(0,0,0,($month -1),($fw_start -$fw_offset +1),$year));
	
	$prev_month = explode("-",$fw_start);
	
	$prev_month_show = $prev_month[2];

 do {
 
	echo '<td valign="top" align="right" width="19" height="18" style="color:grey; background-color:#CCC;">'.$prev_month_show.'</td>';
	
	$prev_month_show++;
	
	$cal_start++;
	
} while ($cal_start<date("w",strtotime($day_first)));

}
// Loop throught the current month

do {

	

	// Check for day variations (needs work)
	if($day_count == $day){
	
	echo '<td valign="top" align="right" width="19" height="18" style="color:black; background-color:#C6FFC6">';
	
	echo $day_count;
	
	} else if(in_multi_array(date("Y-m-d",strtotime($year."-".$month."-".$day_count)),$event)){
	
	echo '<td valign="top" align="right" width="19" height="18" style="color:black; background-color:#FFFFBB">';	
	
	echo "<a href='calendar.php?y=".date("Y",strtotime($year."-".$month."-".$day_count))."&m=".date("m",strtotime($year."-".$month."-".$day_count))."&d=".date("d",strtotime($year."-".$month."-".$day_count))."'>".$day_count."</u>";
	
	} else {
	
	echo '<td valign="top" align="right" width="19" height="18" style="color:black; background-color:#FFF">';	
	
	echo $day_count;
	
	}



	echo '</td>';
	// If the day is Saturday then add a row break and continue
			if($week_count == 6){

				echo '</tr><tr>';

				$week_count = 0;

			} else {

				$week_count++;

			}

		$day_count++;

} while ($day_count<(date("t",strtotime($day_first))+1));

// Loop through the blank days at the end of the calendar
$next_month_count = 1;
	 do{
		echo '<td valign="top" align="right" width="19" height="18" style="color:grey; background-color:#CCC">'.$next_month_count.'</td>';
	$week_count++;
	$next_month_count++;
	} while ($week_count<7);
// Finish the table
echo '</table>';

}

function in_multi_array($needle, $haystack) {
   $in_multi_array = false;
   if(in_array($needle, $haystack)) {
       $in_multi_array = true;
   } else {
       foreach ($haystack as $key => $val) {
           if(is_array($val)) {
               if(in_multi_array($needle, $val)) {
                   $in_multi_array = true;
                   break;
               }
           }
       }
   }
   return $in_multi_array;
}
 
function uuid(){
    return sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
        mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ),
        mt_rand( 0, 0x0fff ) | 0x4000,
        mt_rand( 0, 0x3fff ) | 0x8000,
        mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ) );
} 

function validateString($string,$len){

    if (strlen(trim($string)) >= $len) return true;

}

function formatPhone($string){

	$string = preg_replace( '/[\s\-A-Za-z\(\)\.]/', '', $string);
	return substr($string, 0, 10);

}

function validateEmail($email) {

  if (!ereg("^[^@]{1,64}@[^@]{1,255}$", $email)) {
    return false;
  }

  $email_array = explode("@", $email);
  $local_array = explode(".", $email_array[0]);
  for ($i = 0; $i < sizeof($local_array); $i++) {
     if (!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$", $local_array[$i])) {
      return false;
    }
  }
  if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1])) {
    $domain_array = explode(".", $email_array[1]);
    if (sizeof($domain_array) < 2) {
        return false;
    }
    for ($i = 0; $i < sizeof($domain_array); $i++) {
      if (!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$", $domain_array[$i])) {
        return false;
      }
    }
  }
  return true;
}
?>